<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Building controller
 */
class Building extends REST_Controller
{
    function __construct()
    {
        // Construct the parent class
        parent::__construct();
    }

    /**
     * 楼盘统计基本数据
     * @return json
     */
    public function tongji_get() 
    {
        // 参数
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $buildingCode = $this->get('building_code') ? : '';
        $channelCode = $this->get('channel_code') ? : '';
        $startDate = $this->get('start_date') ? : $yesterday;
        $endDate = $this->get('end_date') ? : $yesterday;

        // 加载模型
        $this->load->model('buildings/viewbuildinglogquick_model', 'viewBuildingLogQuick_model');
        // 表名
        $buildingLogQuickTable = $this->viewBuildingLogQuick_model->get_table();

        // 楼盘记录查询条件
        $buildingLogWhere = "$buildingLogQuickTable.building_name = '{$buildingCode}'";
        // 日期条件
        if (!empty($startDate) && !empty($endDate)) {
            $buildingLogWhere .= " AND $buildingLogQuickTable.visit_time >= '".date("Y-m-d 00:00:00", strtotime($startDate))."' AND $buildingLogQuickTable.visit_time <= '".date("Y-m-d 23:59:59", strtotime($endDate))."'";
        }
        // 渠道条件
        if (!empty($channelCode)) {
            $buildingLogWhere .= " AND $buildingLogQuickTable.channel_name = '{$channelCode}'";
        }
        // 浏览量
        $pvCount = $this->viewBuildingLogQuick_model->select('id')->where($buildingLogWhere)->count_all();
        $uvData = $this->viewBuildingLogQuick_model->select('id')->where($buildingLogWhere)->group_by('cookie')->find_all();
        $ipData = $this->viewBuildingLogQuick_model->select('id')->where($buildingLogWhere)->group_by('ip_address')->find_all();
        $uvCount = $uvData ? count($uvData) : 0;
        $ipCount = $ipData ? count($ipData) : 0;

        // $uvCount = $this->viewBuildingLogQuick_model->db->where($buildingLogWhere)->group_by('cookie')->count_all_results($buildingLogQuickTable);
        // $data = ['pv'=>"{$pvCount}", 'uv'=>"{$uvCount}", 'ip'=>"{$ipCount}", 'building_code'=>$buildingCode, 'channel_code'=>$channelCode, 'start_date'=>$startDate, 'end_date'=>$endDate, 'where'=>$buildingLogWhere, 'last_query'=>$this->viewBuildingLogQuick_model->db->last_query()];
        $data = ['pv'=>"{$pvCount}", 'uv'=>"{$uvCount}", 'ip'=>"{$ipCount}", 'start_date'=>$startDate, 'end_date'=>$endDate];
        $this->response($data);
    }

    /**
     * 楼盘每日自然流量统计查询
     * @return object
     */
    public function freeTraffic_get() 
    {
        // 参数
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $date = $this->get('date') ? : $yesterday;
        // 加载模型
        $this->load->model('buildings/viewbuildinglog_model', 'viewBuildingLog_mode');
        $this->viewBuildingLog_mode->chip_date = date("Ymd", strtotime($date));
        $this->viewBuildingLog_mode->get_table_name(null);
        // 楼盘记录查询条件
        // $buildingLogWhere = "`channel_name` = 'other' AND `source_url` NOT LIKE '%campaign?qd=%'";
        $buildingLogWhere = "`channel_name` = 'other' AND `ip_address` != '125.215.44.105'";
        // 浏览量
        $pvCount = $this->viewBuildingLog_mode->select('id')->where($buildingLogWhere)->not_like("source_url", "campaign?qd=")->count_all();
        $uvData = $this->viewBuildingLog_mode->select('id')->where($buildingLogWhere)->not_like("source_url", "campaign?qd=")->group_by('cookie')->find_all();
        $ipData = $this->viewBuildingLog_mode->select('id')->where($buildingLogWhere)->not_like("source_url", "campaign?qd=")->group_by('ip_address')->find_all();
        $uvCount = $uvData ? count($uvData) : 0;
        $ipCount = $ipData ? count($ipData) : 0;

        $data = ['pv'=>"{$pvCount}", 'uv'=>"{$uvCount}", 'ip'=>"{$ipCount}", 'date'=>$date];
        $this->response($data);
    }

    public function index_post()
    {
        $flag = false;
        $post = $this->post();
        $this->validPost($post);

        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model', 'buildings_info_model');

        $dataField = ['developer_code', 'name', 'nickname', 'code', 'dmp_building_code', 'ave_price', 'open_time', 'pass_time', 'province_id', 'city_id', 'district_id', 'lat', 'lng','status'];
        $data = ['telephone'=>4000756000];
        $infoData = [];
        foreach ($dataField as $val) {
            if (isset($post[$val])) {
                $data[$val] = $post[$val];
            }
        }
        // 写入楼盘表
        $id = $this->buildings_model->insert($data);
        if (is_numeric($id)) {
            // 写入楼盘信息表
            $infoData['building_id'] = $id;
            foreach ($post as $key => $val) {
                if (!in_array($key, $dataField)) {
                    $infoData[$key] = $val;
                }
            }
            if (!isset($infoData['phone_switch'])) $infoData['phone_switch'] = 0;
            if (!isset($infoData['yuyue_switch'])) $infoData['yuyue_switch'] = 0;
            if (!isset($infoData['hx_switch'])) $infoData['hx_switch'] = 0;
            if (!isset($infoData['chat_switch'])) $infoData['chat_switch'] = 0;
            if (!isset($infoData['building_switch'])) $infoData['building_switch'] = 0;
            if (!isset($infoData['lingxi_switch'])) $infoData['lingxi_switch'] = 0;

            if (!isset($infoData['floor_space'])) $infoData['floor_space'] = 0;
            if (!isset($infoData['all_space'])) $infoData['all_space'] = 0;
            if (!isset($infoData['chanquan_n'])) $infoData['chanquan_n'] = 0;
            $infoId = $this->buildings_info_model->insert($infoData);
            if (is_numeric($infoId)) $flag = true;
            $post['id'] = $id;
        }
        $flag ? $this->response(['status'=>true, 'data'=>$post], REST_Controller::HTTP_CREATED) : $this->response(['status'=>false, 'message'=>'数据写入失败'], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
    }

    public function index_patch($code)
    {
        //接受参数
        $patch = $this->patch();
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model', 'buildings_info_model');
        $buildingField = ['developer_code', 'name', 'nickname', 'code', 'dmp_building_code', 'ave_price', 'open_time', 'pass_time', 'province_id', 'city_id', 'district_id', 'lat', 'lng','status'];
        $buildingOne = $this->buildings_model->find_by(['dmp_building_code'=>$code]);
        if(empty($patch) || !$buildingOne) $this->response(['status'=>false, 'message'=>'请求参数错误'], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
        $buildingData = [];
        $buildingInfoData = [];
        foreach ($patch as $key => $value) {
            // in_array($key, $buildingField) ？$buildingData[$key] = $value : $buildingInfoData[$key] = $value; 
            if(in_array($key, $buildingField)){
                $buildingData[$key] = $value;
            }else{
                $buildingInfoData[$key] = $value;
            }
        }
        //更新数据
        $buildingResult = !empty($buildingData) ? $this->buildings_model->update(['id'=>$buildingOne->id], $buildingData) : 0;
        $buildingInfoResult = !empty($buildingInfoData) ? $this->buildings_info_model->update(['building_id'=>$buildingOne->id], $buildingInfoData) : 0;
        if($buildingResult || $buildingInfoResult){
            $this->response(['status'=>true, 'id'=>$buildingOne->id], REST_Controller::HTTP_CREATED);
        }else{
            $this->response(['status'=>false, 'message'=>'更新失败'], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    public function index_get()
    {
        $post = $this->get();
        $this->response($post);
    }

    private function validPost($data)
    {
        $require = ['address'=>'楼盘地址', 'name'=>'楼盘名', 'dmp_building_code'=>'楼盘 code', 'province_id'=>'省份ID', 'city_id'=>'城市ID', 'district_id'=>'区县ID'];
        foreach ($require as $key => $val) {
            if (!isset($data[$key]) || empty($data[$key])) {
                $this->response(['status'=>false, 'message'=>$val.' 不能为空'], REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
                break;
            }
        }
    }
}